package com.github.wxiaoqi.security.admin.rest;

import com.github.wxiaoqi.security.admin.entity.Menu;
import com.github.wxiaoqi.security.admin.entity.ResourceAuthority;
import com.github.wxiaoqi.security.admin.entity.UserRole;
import com.github.wxiaoqi.security.admin.vo.AuthorityMenuTree;
import com.github.wxiaoqi.security.admin.vo.MenuTree;
import com.github.wxiaoqi.security.auth.common.config.UserAuthConfig;
import com.github.wxiaoqi.security.auth.common.util.jwt.IJWTInfo;
import com.github.wxiaoqi.security.auth.common.util.jwt.JWTHelper;
import com.github.wxiaoqi.security.common.rest.BaseController;
import com.github.wxiaoqi.security.common.util.TreeUtil;
import com.github.wxiaoqi.security.admin.biz.MenuBiz;
import com.github.wxiaoqi.security.admin.biz.ResourceAuthorityBiz;
import com.github.wxiaoqi.security.admin.biz.UserBiz;
import com.github.wxiaoqi.security.admin.biz.UserRoleBiz;
import com.github.wxiaoqi.security.admin.constant.AdminCommonConstant;
import org.springframework.beans.factory.annotation.Autowired;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.BeanUtils;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import tk.mybatis.mapper.entity.Example;

import java.util.ArrayList;
import java.util.List;
import java.util.Map;

/**
 * ${DESCRIPTION}
 *
 * @author wanghaobin
 * @create 2017-06-12 8:49
 */
@Controller
@RequestMapping("menu")
public class MenuController extends BaseController<MenuBiz, Menu> {
    @Autowired
    private UserBiz userBiz;
    @Autowired
    private UserRoleBiz userRoleBiz;
    @Autowired
    private UserAuthConfig userAuthConfig;
    @Autowired
    private ResourceAuthorityBiz resourceAuthorityBiz;

    @RequestMapping(value = "/list", method = RequestMethod.GET)
    @ResponseBody
    public List<Menu> list(String title) {
        Example example = new Example(Menu.class);
        if (StringUtils.isNotBlank(title)) {
            example.createCriteria().andLike("title", "%" + title + "%");
        }
        return baseBiz.selectByExample(example);
    }

    @RequestMapping(value = "/tree", method = RequestMethod.GET)
    @ResponseBody
    public List<MenuTree> getTree(@RequestParam Map<String, Object> param) {
        Example example = new Example(Menu.class);
        String title = (String) param.get("title");
        String token = (String) param.get("token");
        if (StringUtils.isNotBlank(title)) {
            example.createCriteria().andLike("title", "%" + title + "%");
        }
        return getMenuTree2(baseBiz.selectByExample(example), AdminCommonConstant.ROOT,token);
    }



    @RequestMapping(value = "/system", method = RequestMethod.GET)
    @ResponseBody
    public List<Menu> getSystem() {
        Menu menu = new Menu();
        menu.setParentId(AdminCommonConstant.ROOT);
        return baseBiz.selectList(menu);
    }

    @RequestMapping(value = "/menuTree", method = RequestMethod.GET)
    @ResponseBody
    public List<MenuTree> listMenu(Integer parentId) {
        try {
            if (parentId == null) {
                parentId = this.getSystem().get(0).getId();
            }
        } catch (Exception e) {
            return new ArrayList<MenuTree>();
        }
        List<MenuTree> trees = new ArrayList<MenuTree>();
        MenuTree node = null;
        Example example = new Example(Menu.class);
        Menu parent = baseBiz.selectById(parentId);
        example.createCriteria().andLike("path", parent.getPath() + "%").andNotEqualTo("id",parent.getId());
        return getMenuTree(baseBiz.selectByExample(example), parent.getId());
    }

    @RequestMapping(value = "/authorityTree", method = RequestMethod.GET)
    @ResponseBody
    public List<AuthorityMenuTree> listAuthorityMenu() {
        List<AuthorityMenuTree> trees = new ArrayList<AuthorityMenuTree>();
        AuthorityMenuTree node = null;
        for (Menu menu : baseBiz.selectListAll()) {
            node = new AuthorityMenuTree();
            node.setText(menu.getTitle());
            BeanUtils.copyProperties(menu, node);
            trees.add(node);
        }
        return TreeUtil.bulid(trees, AdminCommonConstant.ROOT);
    }

    @RequestMapping(value = "/user/authorityTree", method = RequestMethod.GET)
    @ResponseBody
    public List<MenuTree> listUserAuthorityMenu(Integer parentId){
        Long userId = userBiz.getUserByUsername(getCurrentUserName()).getUserId();
        try {
            if (parentId == null) {
                parentId = this.getSystem().get(0).getId();
            }
        } catch (Exception e) {
            return new ArrayList<MenuTree>();
        }
        return getMenuTree(baseBiz.getUserAuthorityMenuByUserId(userId),parentId);
    }

    @RequestMapping(value = "/user/system", method = RequestMethod.GET)
    @ResponseBody
    public List<Menu> listUserAuthoritySystem() {
        int userId = userBiz.getUserByUsername(getCurrentUserName()).getId();
        return baseBiz.getUserAuthoritySystemByUserId(userId);
    }

    private List<MenuTree> getMenuTree(List<Menu> menus,int root) {
        List<MenuTree> trees = new ArrayList<MenuTree>();
        MenuTree node = null;
        for (Menu menu : menus) {
            node = new MenuTree();
            BeanUtils.copyProperties(menu, node);
            node.setLabel(menu.getTitle());
            trees.add(node);
        }
        return TreeUtil.bulid(trees,root) ;
    }
    
    private List<MenuTree> getMenuTree2(List<Menu> menus,int root,String token) {
        List<MenuTree> trees = new ArrayList<MenuTree>();
        MenuTree node = null;
        Integer roleId = 0;
        try {
    		IJWTInfo info = JWTHelper.getInfoFromToken(token, userAuthConfig.getPubKeyByte());
    		String userId = info.getXId();
    		UserRole userRole = new UserRole();
    		userRole.setUserId(Long.valueOf(userId));
    		List<UserRole>  userRoleList = userRoleBiz.selectList(userRole);
    		UserRole userRoleOther = userRoleList.get(0);
    		roleId = userRoleOther.getRoleId();
		} catch (Exception e) {
			e.printStackTrace();
		}
        ResourceAuthority resourceAuthority = new ResourceAuthority(); 
        resourceAuthority.setAuthorityId(String.valueOf(roleId));
        resourceAuthority.setResourceType("menu");
        List<ResourceAuthority> resourceAuthorityList = resourceAuthorityBiz.selectList(resourceAuthority);
    	for (Menu menu : menus) {
       	 //判断一下有没有这个菜单的权限
        	if(roleId != 1){
	           	for (ResourceAuthority ra : resourceAuthorityList) {
	   				if(menu.getId() == Integer.valueOf(ra.getResourceId())){
	   		            node = new MenuTree();
	   		            BeanUtils.copyProperties(menu, node);
	   		            node.setLabel(menu.getTitle());
	   		            trees.add(node);
	   		            break;
	   				}
	   			}
          }else {
        	  node = new MenuTree();
        	  BeanUtils.copyProperties(menu, node);
        	  node.setLabel(menu.getTitle());
        	  trees.add(node);
          }
    	}
    return TreeUtil.bulid(trees,root) ;
    }


}
